function try_login(next_url, hint) {
  if (typeof(next_url) != 'undefined') {
    $("#login_dialog form").append($("<input>").attr('type', 'hidden').attr('name', 'next_url').val(next_url));
  }
  if (typeof(hint) == 'undefined') {
    hint = "";
  } 
  $("#login_dialog #hint").text(hint);
  $("#login_dialog").dialog('open');
}

/* this function load comments pertainning to certain note, and add to the element
 * specified by 'comments_e', and return the loaded comments
 * */
function load_comments(comments_e, note_id) {
  var ret = null;
  $.ajax({
    async: false,
    type: "GET",
    timeout: 3,
    url: "/notes/api/comment",
    data: {'note_id': note_id},
    success: function (msg, status) {
      var comments = eval(msg);
      ret = comments;
      var comment_form = comments_e.children('form');
      for (i in comments) {
        var comment = comments[i]; 
        var new_comment_e = $(".mini_comment_prototype").clone();
        new_comment_e.removeClass("mini_comment_prototype").removeClass("hidden").addClass("mini_comment");
        new_comment_e.children('.mini_comment_avatar').attr('src', comment.avatar).attr('width', 32).attr('height', 32);
        new_comment_e.children('.mini_comment_author').html("<a href=\"/member/space/"+comment.author+"/\">"+comment.author+"</a>:");
        new_comment_e.children('.mini_comment_content').text(comment.content);
        new_comment_e.children('.mini_comment_pub_date').text(comment.pub_date);
        comment_form.before(new_comment_e);
      }
    }
  });
  return ret;
}

/* post a comment pertainning to certain note, if success, return the comment it self
 * else throw an exception
 * */
function post_comment(content, note_id) {
  var ret = null;
  var req = $.ajax({
    async: false,
    timeout: 3,
    url: '/notes/api/comment',
    type: 'POST', 
    data: {content: content, note_id: note_id},
    success: function (msg, status) {
      ret = eval(msg)[0];
    },
    error: function (req, msg, e) {
      if (req.status == 403) {
        throw {name: 'forbidden', message: 'login required'};
      } else {
        throw {name: 'unknown', message: ''};
      }
    }
  });
  
  return ret;
}

function prepend_comment(comments_e, comment) {
  var new_comment_e = $(".mini_comment_prototype").clone();
  new_comment_e.removeClass("mini_comment_prototype").removeClass("hidden").addClass("mini_comment");
  new_comment_e.children('.mini_comment_avatar').attr('src', comment.avatar).attr('width', 32).attr('height', 32);
  new_comment_e.children('.mini_comment_author').html("<a href=\"/member/space/"+comment.author+"/\">"+comment.author+"</a>:");
  new_comment_e.children('.mini_comment_content').text(comment.content);
  new_comment_e.children('.mini_comment_pub_date').text(comment.pub_date);
  comments_e.prepend(new_comment_e);
}

/* this function read notes from a web service and 
   append the notes to an element
   * count - number of notes to sent
   * max_id - the max id of the returned the notes should be less than
    this max_id 
    returned value is an array with 2 elements, the first is the number of
    notes returned, the second is the max id of these notes.
   */ 
function append_notes(e, count, max_id, url) {        
  var ret;
  var data;
  if (max_id == Infinity) {
    data = {'count': count};
  } else {
    data = {'count': count, 'max_id': max_id};
  }
  $.ajax({
    type: 'GET',
    timeout: 3,
    async: false,
    url: url,
    data: data,
    success: function (msg, status) {
      var notes = eval(msg);
      var max_id = 0;
      if (notes.length > 0) {
        max_id = notes[notes.length-1].id;
      }
      ret = [notes.length, max_id];
      for (var i=0; i < notes.length; ++i) {
        var note = notes[i];
        var new_note_e = $(".mini_note_prototype").clone();
        new_note_e.removeClass('mini_note_prototype').removeClass('hidden').addClass("mini_note").addClass('ui-widget');
        new_note_e.children("input[type='hidden']").val(note.id);
        new_note_e.children('.mini_note_avatar').attr('src', note.avatar).attr('width', 48).attr('height', 48);
        new_note_e.children('.mini_note_author').html("<a href=\"/member/space/"+note.author+"/\">"+note.author+"</a>:");
        new_note_e.children('.mini_note_content').text(note.content);
        new_note_e.children('.mini_note_pub_date').text(note.pub_date);
        new_note_e.children("a[href='#toggle_comment']").text(gettext("comments")+"("+note.comments_cnt+")");
        new_note_e.children(".mini_note_comments").hide();
        new_note_e.children("a[href='#toggle_comment']").toggle(
          function() {
            var note_id = $(this).parent().children("input[type='hidden']").val();
            var comments_e = $(this).nextAll(".mini_note_comments");
            // get the comments if necessary
            if (comments_e.children(".mini_comment").length == 0) {
              comments = load_comments(comments_e, note_id);
              comments_e.children('form').max_length({max_length: 140});
              comments_e.children('form').submit((function (note_id) {
                return function () {
                  try {
                    var comment = post_comment($(this).children('input:first').val(), note_id);
                  } catch (e) {
                    if (e.name == "forbidden") {
                      try_login(window.location.href, gettext("please login to post comment"));
                    }
                  }
                  $(this).children('text_area').val("");
                  if (comment) {
                    prepend_comment($(this).parent(), comment)
                  } 
                  return false;
                };
              })(note_id)); 
            }
            comments_e.slideDown('fast');
            $(this).next().removeClass('ui-icon-circle-plus').addClass('ui-icon-circle-minus');
          },
          function () {
            $(this).nextAll(".mini_note_comments").hide();
//             new_note_e.children("mini_note_comments").hide();
            $(this).next().removeClass('ui-icon-circle-minus').addClass('ui-icon-circle-plus');
          }
        );
        e.append(new_note_e);
      }
    }
  });
  return ret;
}

/* this function prepend A note to an element
   * e - element to be prepended
   * note - note to prepend
   */ 
function prepend_note(e, note) {        
  var new_note_e = $(".mini_note_prototype").clone();
  new_note_e.children("input[type='hidden']").val(note.id);
  new_note_e.removeClass('mini_note_prototype').removeClass('hidden').addClass("mini_note");
  new_note_e.children('.mini_note_avatar').attr('src', note.avatar).attr('width', 48).attr('height', 48);
  new_note_e.children('.mini_note_author').html("<a href=\"/member/space/"+note.author+"/\">"+note.author+"</a>:");
  new_note_e.children('.mini_note_content').text(note.content);
  new_note_e.children('.mini_note_pub_date').text(note.pub_date);
  new_note_e.children("a[href='#toggle_comment']").text(gettext("comments")+"("+note.comments_cnt+")");
  new_note_e.children(".mini_note_comments").hide();
  new_note_e.children("a[href='#toggle_comment']").toggle(function() {
      var note_id = $(this).parent().children("input[type='hidden']").val();
      var comments_e = $(this).nextAll(".mini_note_comments");
      // get the comments if necessary
      if (comments_e.children(".mini_comment").length == 0) {
        comments = load_comments(comments_e, note_id);
        comments_e.children('form').max_length({max_length: 140});
        comments_e.children('form').submit((function (note_id) {
            return function () {
              try {
                var comment = post_comment($(this).children('input:first').val(), note_id);
              } catch (e) {
                if (e.name == "forbidden") {
                  try_login(window.location.href, gettext("please login to post comment"));
                }
              }
              $(this).children('input:first').val("");
              if (comment) {
                prepend_comment($(this).parent(), comment)
              } 
              return false;
            };
         })(note_id)); 
      }
      comments_e.slideDown('fast');
      $(this).next().removeClass('ui-icon-circle-plus').addClass('ui-icon-circle-minus');
    },
    function () {
      $(this).nextAll(".mini_note_comments").hide();
      //             new_note_e.children("mini_note_comments").hide();
      $(this).next().removeClass('ui-icon-circle-minus').addClass('ui-icon-circle-plus');
    }
  );
  e.prepend(new_note_e);
}

$(function () {
  $("#login_dialog").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 370,
    modal: true,
    buttons: {
      cancel: function () {
        $(this).dialog('close');
      },
      login: function() {
        $("#login_dialog form").submit();
      }
    }
  });

  $("#login_dialog form").submit(function () {
    var tips_e = $("#login_dialog #tips").text("");
    var name = $.trim($('#login_dialog #login_username').val());
    var password = $.trim($("#login_dialog #login_password").val());
    if (name == "") {
      tips_e.text(gettext("username is required"));
      return false;
    }
    if (password == "") {
      tips_e.text(gettext("password is required"));
      return false;
    }
    data = {'username': name, 
        'password': password};
    var req = $.ajax({
      url: "/accounts/api/user_valid",
      data: data,  
      async: false,
      cache: false,
    });
    if (req.status == 404) {
      var s = req.responseText;
      tips_e.text(s);
      return false;
    } 
    return true;
  });
    
  $(".login_link").click(function () {
     try_login();
     return false;
  });
});
